package cn.jdemo.guava.algorithm;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnel;
import com.google.common.hash.Funnels;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;

/**
 * 布隆过滤
 * @see BloomFilter#create(Funnel, int expectedInsertions) Funnel 漏斗；expectedInsertions 预期的插入
 *
 *
 * @date 2021/1/6
 */
public class Demo01_BloomFilter {
    public static void main(String[] args) {
        test01();
        test02();
    }

    /**
     * 输出内容
     * 是否可能存在: true
     * 是否可能存在: false
     * 是否可能存在: true
     * 
     * @see BloomFilter#create(Funnel, int)
     * @see Funnels#longFunnel()
     */
    public static void test01() {
        Funnel<Long> longFunnel = Funnels.longFunnel();
        BloomFilter<Long> longBloomFilter = BloomFilter.create(longFunnel, 10);
        longBloomFilter.put(1024L);
        longBloomFilter.put(1000L);

        System.out.println("是否可能存在: " +longBloomFilter.mightContain(1000L));
        System.out.println("是否可能存在: " +longBloomFilter.mightContain(1001L));
        System.out.println("是否可能存在: " +longBloomFilter.mightContain(1024L));
    }

    /**
     * ???
     * 数据1: 73464968921614340
     * 数据2: 168041110852075520
     */
    public static void test02() {
        Funnel<Long> longFunnel = Funnels.longFunnel();
        BloomFilter<Long> longBloomFilter = BloomFilter.create(longFunnel, 10);
        longBloomFilter.put(1024L);
        longBloomFilter.put(1000L);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        // byte[] bytes = new byte[0];
        try {
            longBloomFilter.writeTo(byteArrayOutputStream);
            // bytes = byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }

        ByteArrayInputStream byteArrayInputStream= new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        DataInputStream dataInputStream = new DataInputStream(byteArrayInputStream);
        try {
            System.out.println("数据1: " +dataInputStream.readLong());
            System.out.println("数据2: " +dataInputStream.readLong());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
